<?php

class Application_Model_DbTable_ShopKeyword extends Zend_Db_Table_Abstract
{

    protected $_name = 'Shop_keyword';

    public function assign($shop_id, $keywords){
        if(count($keywords)==0) return;

        $keys_db = new Application_Model_DbTable_Keyword();

        //insert every keyword except existing one
        foreach($keywords as $keyword){
            $keyword = trim($keyword);
            if(strlen($keyword)<=0) continue;

            $keyword = strtolower($keyword);
            $key = $keys_db->fetchRow("name = '$keyword'");

            // If keyyword exists already, assign shop with keyword
            if($key) {
                $data = array("shop_id"=>$shop_id,"keyword_id"=>$key->keyword_id);
                $this->insert($data);
                continue;
            }

            // Else, add new keyword then assign
            $data = array("name"=>$keyword);
            $keys_db->insert($data);
            $key = $keys_db->fetchRow("name = '$keyword'");
            $data = array("shop_id"=>$shop_id,"keyword_id"=>$key->keyword_id);
            $this->insert($data);
        }
    }

    public function unassign($shop_id){
        $this->delete("shop_id = ".(int)$shop_id);
    }
}

